import request from '../../utils/request';
import { getUserLevel } from '../../utils/constants';

// pages/rank/rank.js
Page({
  data: {
    userInfo: {},
    rankList: [],
    userRank: 0,
    loading: true
  },

  onLoad: function (options) {

  },

  onShow: function () {
    // 获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      const userInfo = app.globalData.userInfo;
      // 获取用户等级信息
      const levelInfo = getUserLevel(userInfo.score || 0);
      userInfo.level = levelInfo.name;
      userInfo.levelClass = levelInfo.levelClass;
      userInfo.className = levelInfo.className;
      userInfo.avatarClass = levelInfo.avatarClass;

      this.setData({
        userInfo
      });
    }

    // 加载排行榜数据
    this.loadRankData();
  },

  // 加载排行榜数据
  loadRankData: function () {
    this.setData({ loading: true });

    request({
      url: '/leaderboard',
      method: 'GET',
      data: {
        openId: this.data.userInfo.openId
      }
    })
      .then(res => {
        const rankList = res.data.list.map((user, index) => {
          // 获取用户等级信息
          const levelInfo = getUserLevel(user.score || 0);
          return {
            ...user,
            rank: index + 1,
            level: levelInfo.name,
            levelClass: levelInfo.levelClass,
            className: levelInfo.className,
            avatarClass: levelInfo.avatarClass
          };
        });


        this.setData({
          rankList,
          userRank:res.data.userRank,
          loading: false
        });
      })
      .catch(err => {
        console.error('获取排行榜失败', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '获取排行榜失败',
          icon: 'none'
        });
      });
  },


  // 刷新排行榜
  refreshRank: function () {
    this.loadRankData();
  },

  // 返回首页
  navigateToHome: function () {
    wx.switchTab({
      url: '/pages/index/index'
    });
  }
});